package com.ruoyi.api.controller;

import com.ruoyi.common.constant.BizCodeConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.exception.api.FaultException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.util.RedisCacheUtil;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.dto.ApiUserVo;
import com.ruoyi.user.service.IUserService;
import org.springframework.http.HttpStatus;

import java.util.Objects;

/**
 * Created by sea on 2019/12/28.
 */
public class ApiBaseController extends BaseController {
    protected RedisCacheUtil redisCacheUtil;

    protected IUserService userService;

    /**
     * 获取api登录用户id
     *
     * @return
     */
    protected Long getApiLoginMember() {
        String token = ServletUtils.getRequest().getHeader("x-token");
        if (redisCacheUtil == null) {
            redisCacheUtil = SpringUtils.getBean(RedisCacheUtil.class);
        }
        return redisCacheUtil.get(String.format("%s%S", Constants.API_TOKEN_CACHE_KEY, token), Long.class);
    }

    protected Long checkLogin() {
        Long memberId = getApiLoginMember();
        if (memberId == null || memberId == 0) {
            throw new FaultException(BizCodeConstants.NOT_LOGIN, "please login", HttpStatus.FORBIDDEN);
        }
        return memberId;
    }

    protected ApiUserVo checkLoginAndGetMember() {
        Long memberId = getApiLoginMember();
        if (memberId == null || memberId == 0) {
            throw new FaultException(BizCodeConstants.NOT_LOGIN, "please login");
        }
        ApiUserVo apiMemberVo = redisCacheUtil.get(String.format("%s%S", Constants.MEMBER_CACHE_KEY, memberId), ApiUserVo.class);
        if (apiMemberVo == null) {
            apiMemberVo = getUserVo(memberId);
        }
        // TODO 判断用户是否已经禁用
        return apiMemberVo;
    }


    private ApiUserVo getUserVo(Long userId) {
        if (userService == null) {
            userService = SpringUtils.getBean(IUserService.class);
        }
        User user = this.userService.selectUserById(userId);
        if (Objects.isNull(user)) {
            return new ApiUserVo();
        }
        ApiUserVo userVo = new ApiUserVo();
        userVo.setAvatar(user.getAvatar());
        userVo.setGender(user.getGender());
        userVo.setNickName(user.getNickName());
        userVo.setPhone(user.getPhone());
        userVo.setUserId(user.getKeyId());
        redisCacheUtil.set(String.format("%s%S", Constants.MEMBER_CACHE_KEY, user.getKeyId()), userVo, Constants.TOKEN_EXPIRE_TIME);
        return userVo;
    }
}
